<template>
    <ui-container :scrollGoTop="0" :full="true" :scrollbar="false">
        <view class="my_wrapper">

            <view class="wrapper">
                <!-- #ifndef H5 -->
                <global-nav-bar @setHeight="setHeight" left-icon="back" title="保养整改问题" :fixed="true"
                    backgroundColor="#2C2C2C" color="#fff"></global-nav-bar>
                <!-- #endif -->

                <view class="tabs">
                    <view v-for="(item, index) in tabs" :key="index"
                        :class="['tabs-item', tabIdx == item.key ? 'act' : '']" @click="changeTab(item.key)">{{
                            item.label }}({{ item.total }})</view>
                </view>

                <view class="item_search">
                    <view class="search-bar">
                        <uni-search-bar class="uni-search-bar" v-model="searchVal" clearButton="auto"
                            cancelButton="none" placeholder="搜索项目/电梯关键词" @blurs="searchInput" />
                    </view>
                    <view class="search-bar-right">
                        <filterModel ref="filterModel" :showSelect="false" :disabled="disabledFilter" :all="allFilter"
                            :userIds="userIds" :csd="csd" :filterObj="obj" :isShowArr="tabIdx" @filterd="filterd">
                        </filterModel>
                    </view>
                </view>
            </view>
            <view class="item_content">
                <scroll-view @scrolltolower="scrolltolower" :style="{ height: pageHight - 100 + 'px' }" :scroll-y="true"
                    @scroll="scroll" :scroll-top="scrollGoTop">
                    <view class="content_L" @click.stop="">
                        <view style="background: #fff;padding: 24rpx 20rpx;margin-bottom: 16rpx;"
                            v-for="(item, index) in questionList" :key="index" @click="toDetail(item)">
                            <view class="marginTop" style="display: flex;justify-content: space-between;">
                                <view style="color: #333333;font-weight: 500;font-size: 28rpx;width: 70%;">{{
                                    item.buildingName
                                    + '-' + item.elevatorAddress }}</view>
                                <view :style="{ color: item.appealType == 1 ? '#0091FF' : '#FA6400' }"
                                    v-if="tabIdx != 2">
                                    {{ item.appealType == 1 ? '可申诉' : '不可申诉' }}
                                    <uni-icons :color="item.appealType == 1 ? '#0091FF' : '#FA6400'" size="16"
                                        type="arrowright" />
                                </view>
                            </view>
                            <view class="marginTop">
                                <text class="question-label">问题总数：</text>
                                <text class="question-count">{{ item.questionCount }}</text>
                            </view>
                            <view class="marginTop">
                                <text class="question-label">申诉状态：</text>
                                <text class="question-count">{{ !item.appealStatus ? '-' : item.appealStatus == 1 ?
                                    '待申诉' : '已申诉' }}</text>
                            </view>
                            <view class="marginTop">
                                <text class="question-label">申诉结果：</text>
                                <text class="question-tag" :style="{
                                    borderColor: !item.appealResult ? 'transparent' : item.appealResult == 1 ? '#FA6400' : item.appealResult == 2 ? '#16BF99' : '#E02020',
                                    color: !item.appealResult ? '#333' : item.appealResult == 1 ? '#FA6400' : item.appealResult == 2 ? '#16BF99' : '#E02020'
                                }">
                                    {{ !item.appealResult ? '-' : item.appealResult == 1 ? '待审核' : item.appealResult
                                        == 2 ? '审核通过' : '审核不通过' }}
                                </text>
                            </view>
                            <view class="marginTop">
                                <text class="question-label">保养人员：</text>
                                <text class="question-count">{{ item.planUserNames }}</text>
                            </view>
                            <view class="marginTop">
                                <text class="question-label">完成时间：</text>
                                <text class="question-count">{{ item.planEndTime }}</text>
                            </view>
                        </view>
                        <uni-load-more :status="state" :contentText="contentText"></uni-load-more>
                    </view>
                </scroll-view>
            </view>
            <view-top ref="viewTop" :scrollTop="scrollTop" :distance="100" @goTop="goTop"></view-top>

        </view>
    </ui-container>
</template>

<script>
import filterModel from './components/filter-modelPlus.vue';
import GlobalNavBar from '@/components/uni-nav-bar/global-nav-bar';
import unisearchbar from '@/components/uni-search-bar/uni-search-bar.vue';
import { mapState } from 'vuex';
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
import uiContainer from '@/components/ui-container/ui-container.vue';
import viewTop from '@/components/viewTop/viewTop.vue';
import { getAppealQuestion } from '@/apis/appeal.js';
import { mergeList } from '@/utils/utils.js';
 
export default {
	data() {
		return {
			tabIdx: 0,
			mheight: 0,
			scrollGoTop: 0, // 返回顶部
			scrollTop: 0,  // 滚动距离
			showFilter: false,
			allFilter: true,
			disabledFilter: false,
			csd: {}, // 筛选
			contentText: {
				contentdown: '上拉显示更多',
				contentrefresh: '正在加载...',
				contentnomore: '~ 已经到底了 ~'
			},
			pageHight: uni.getSystemInfoSync().windowHeight,
			elevatorList: [],
			state: '',
			eleState: '',
			eleShow: true, // 显示电梯列表更多状态
			totalPage: 0,
			obj: {
				current: 1,
				size: 20,
                appealStatusStr:'',
			},
			searchVal: '',
			title: '保养整改问题',
			tabs: [
				{
					label: '全部',
					total: 0,
					key: 0
				},
				{
					label: '待申诉',
					total: 0,
					key: 1
				},
				{
					label: '已申诉',
					total: 0,
					key: 2
				}
			],
			questionList: [],
		};
	},
	components: {
		GlobalNavBar,
		filterModel,
		unisearchbar,
		uniNavBar,
		uiContainer,
		viewTop,
	},
	computed: {
		...mapState('user', ['userinfo'])
	},
	async onShow() {
		await this.initElevatorGroup();
	},
	onUnload() {
		uni.$emit('appealCount');
	},
	mounted() {},
	methods: {
		toDetail(item) {
			uni.navigateTo({
				url: '/subpages/correction/appealDetail?planId=' + item.planId + '&elevatorId=' + item.elevatorId + '&id=' + item.id,
			});
		},
		changeTab(idx) {
			console.log(idx, 'idx');
			this.tabIdx = idx;
			this.obj = {};
			this.$refs.filterModel.activeTxt = false;
			this.obj.current = 1;
			this.obj.size = 20;
			if (idx == 1) {
				this.obj.appealStatusStr = '1';
			} else if (idx == 2) {
				this.obj.appealStatusStr = '2';
			} else {
				this.obj.appealStatusStr = '';
			}
			this.statusActive = 0;
			this.searchVal = '';
			this.questionList = [];
			this.$refs.filterModel.$refs['filter-drawer'].handleReset(); // 重置筛选器
		},

		mergeQuestionListById : (existingList, newRecords) =>{
			// 创建现有数据的 Map，key 为 id，value 为 { item, index }
			const existingMap = new Map();
			existingList.forEach((item, index) => {
				existingMap.set(item.id, { item, index });
			});
            
			// 记录操作统计
			let updateCount = 0;
			let insertCount = 0;
			const result = [...existingList]; // 复制现有列表
            
			newRecords.forEach(newRecord => {
				if (existingMap.has(newRecord.id)) {
					// ID 存在，更新现有记录
					const { index } = existingMap.get(newRecord.id);
					result[index] = { ...result[index], ...newRecord }; // 合并更新，保留原有字段
					updateCount++;
				} else {
					// ID 不存在，添加新记录
					result.push(newRecord);
					insertCount++;
				}
			});
            
			console.log(`合并完成 - 更新: ${updateCount}条, 新增: ${insertCount}条, 总计: ${result.length}条`);
			return result;
		},
        
		async initElevatorGroup() {
			console.log('#initElevatorGroup initElevatorGroup 被调用', this.id);
			console.trace();
    
			this.obj.keyword = this.searchVal;
			console.log('#initElevatorGroup this.questionList = []; 当前列表长度', this.questionList.length);
			try {
				const [listRes, allTotalRes, pendingTotalRes, completedTotalRes] = await Promise.all([
					getAppealQuestion({ ...this.obj, currentId: this.userinfo.user_id,appealStatusStr:this.obj.appealStatusStr }),
					getAppealQuestion({ currentId: this.userinfo.user_id }),
					getAppealQuestion({ appealStatusStr: '1', currentId: this.userinfo.user_id }),
					getAppealQuestion({ appealStatusStr: '2', currentId: this.userinfo.user_id })
				]);

				this.questionList = mergeList(this.questionList, listRes.data.records);
				this.totalPage = listRes.data.total;

				this.tabs[0].total = allTotalRes.data.total;
				this.tabs[1].total = pendingTotalRes.data.total;
				this.tabs[2].total = completedTotalRes.data.total;

				console.log('#initElevatorGroup Promise.all 调用完成');
			} catch (error) {
				console.error('#initElevatorGroup Promise.all 调用出错:', error);
			}
		},
		setHeight(n) {
			this.mheight = n;
			this.pageHight = this.pageHight - n;
		},
		goTop() {
			this.scrollGoTop = 1;
			this.$nextTick(() => {
				this.scrollGoTop = 0;
			});
		},
		scroll(e) {
			this.scrollTop = e.target.scrollTop;
		},
		// 筛选器
		async filterd(res) {
			console.log(res, '筛选器');
			this.obj.current = 1;
			this.totalPage = 0;
			if (res.choosed && Object.keys(res.choosed).length > 0) {
				for (const key in res.choosed) {
					if (res.choosed.hasOwnProperty(key)) {
						this.obj[key] = res.choosed[key].join(',');
					}
				}
			}
			this.obj.planDateStart = res.dateObj.planBeginDate ? res.dateObj.planBeginDate + ' 00:00:00' : '';
			this.obj.planDateEnd = res.dateObj.planEndDate ? res.dateObj.planEndDate + ' 23:59:59' : '';
			this.obj.planEndTimeStart = res.dateObj.startTime ? res.dateObj.startTime + ' 00:00:00' : '';
			this.obj.planEndTimeEnd = res.dateObj.endTime ? res.dateObj.endTime + ' 23:59:59' : '';

			this.state = '';
			this.questionList = [];

			await this.initElevatorGroup();
		},
		async scrolltolower() {
			if ((this.obj.size * this.obj.current) < this.totalPage) {
				this.obj.current += 1;
				await this.initElevatorGroup();
			} else {
				this.state = 'noMore';
			}
		},
		// 搜索
		async searchInput(res) {
			this.obj.current = 1;
			if (res) {
				this.obj.buildingName = res;
			} else {
				this.obj.buildingName = '';
			}
			this.questionList = [];
			await this.initElevatorGroup('act');
		},

		// 跳转项目详情
		toItemDetial(item) {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uni.navigateTo({
				url: '/pageModules/projectInfo/detail?id=' + item.buildingId,
				success: () => {
					uni.hideLoading();
				},
				fail: () => {
					uni.hideLoading();
				}
			});
			// }
		},
	}
};
</script>

<style lang="scss">
page {
    background: #f8f8f8;
}

.my_wrapper {
    overflow-y: auto;
    overflow-x: hidden;

    .wrapper {
        position: sticky;
        z-index: 10;
        top: 0;
        left: 0;
        right: 0;
        background-color: #fff;

        .item_search {
            display: flex;
            background: #ffffff;
            align-items: center;

            .search-bar {
                width: 600rpx;
                height: 64rpx;
                margin: 20rpx;
                box-sizing: border-box;
                background: #f6f6f6;
                border-radius: 8rpx;
                display: flex;
                align-items: center;

                .uni-search-bar {
                    /deep/ .uni-searchbar {
                        padding: 0;
                    }

                    /deep/ .uni-searchbar__box {
                        width: 600rpx;
                        height: 64rpx;
                        justify-content: flex-start;
                        font-size: 26rpx;
                        color: #ccc;
                        background-color: #f6f6f6;
                        border: 0;
                        border-radius: 8rpx;
                    }

                    /deep/ .uni-icons {
                        width: 40rpx;
                        height: 40rpx;
                    }

                    /deep/ .uni-searchbar__text-placeholder {
                        margin: 0;
                    }

                    /deep/ .uni-searchbar__box-search-input {
                        border: 0;
                        padding: 0;
                    }
                }

                image {
                    width: 40rpx;
                    height: 40rpx;
                }
            }

            .search-bar-right {
                display: flex;
                flex: 1;
                align-items: center;
                font-size: 26rpx;
                color: #333;

                image {
                    width: 32rpx;
                    height: 32rpx;
                }
            }

        }

        .tabs {
            display: flex;
            align-items: flex-end;
            border-bottom: 2rpx solid #eeeeee;
            height: 74rpx;

            &-item {

                display: flex;
                align-items: center;
                justify-content: center;
                transition: .3s all;
                color: #93b1c7;
                font-size: 26rpx;
                border-bottom: 4rpx solid #ffffff;
                margin: 0 20rpx;
                padding: 16rpx 0;

            }

            .act {
                border-color: #0091ff;
                color: #0091ff;
                font-size: 30rpx;
                font-weight: bold;
            }

        }

        .approveStatus {
            padding: 20rpx;
            display: flex;
            flex-direction: row;
            width: 100%;
            white-space: nowrap;
            border-bottom: 2rpx #eee solid;

            .apptop {
                font-size: 26rpx;
                padding: 6rpx 20rpx;
                color: #666;
                margin-right: 15rpx;
                border-radius: 26rpx;
                background-color: #f3f6f8;

            }

            .active {
                color: #0091FF;
                background-color: #dcf0ff;
            }
        }

    }

    .item_content {
        display: flex;
        width: 710rpx;
        margin: 0 auto;
        overflow: auto;

        .content_L {
            width: 710rpx;
            border-radius: 8rpx;
            padding-top: 16rpx;

            .marginTop {
                margin-top: 8rpx;
            }

            .L_text {
                background-color: #ffffff;
                width: 710rpx;
                display: flex;
                flex-direction: column;
                margin-bottom: 20rpx;

                .L_container {
                    display: flex;
                    width: 710rpx;
                }

                .container_left {
                    width: 60rpx;
                    margin: 40rpx 20rpx 20rpx 20rpx;

                    image {
                        width: 50rpx;
                        height: 50rpx;
                    }
                }

                .container_Cont {
                    flex: 1;
                    margin: 20rpx 20rpx 0 0;
                }

                .container_right {
                    display: flex;
                    width: 150rpx;

                    .trrow {
                        margin-top: 15rpx;

                        view {
                            width: 18rpx;
                            height: 18rpx;
                            border-left: 2rpx #999999 solid;
                            border-bottom: 2rpx #999999 solid;
                            transform: rotate(-45deg);
                            margin-top: 30rpx;
                        }
                    }

                }

                .L_one {
                    display: block;
                    font-size: 28rpx;
                    font-weight: 600;
                    color: #333333;
                }

                .L_two {
                    display: block;
                    font-size: 24rpx;
                    color: #999999;
                    margin: 5rpx 0 24rpx 0;
                    width: 550rpx;
                }

                .L_tree {
                    padding-bottom: 24rpx;
                    display: flex;
                    font-size: 24rpx;
                    width: 250rpx;

                    .tips_item {
                        font-size: 24rpx;
                        font-weight: 400;
                        color: #666666;
                    }

                    .projectMsg {
                        color: #0091ff;
                        display: flex;
                        font-size: 24rpx;
                        flex: 1;
                    }
                }
            }

            .lines {
                width: 680rpx;
                margin: 0 auto;
                border-bottom: 2rpx solid #eeeeee;
            }

            .content {
                display: flex;
                flex-direction: row;
                max-height: 600rpx;
                padding-bottom: 30rpx;
                width: 680rpx;
                overflow-y: auto;
                margin: 0 auto;

                .cont_L {
                    width: 680rpx;

                    .contElevar {
                        padding: 30rpx 0rpx;
                        font-size: 24rpx;
                        display: flex;
                        position: relative;

                        .contElevar_Left {
                            flex: 0 0 480rpx;
                            margin-right: 20rpx;

                            .contTitle {
                                .redTag {
                                    font-size: 24rpx;
                                    font-weight: 500;
                                    background: #fde6e6;
                                    color: #e02020;
                                    border: 2rpx solid #fc9e9e;
                                    border-radius: 4rpx;
                                    padding: 0 10rpx 1rpx 10rpx;
                                    margin-left: 12rpx;
                                    white-space: nowrap;
                                }

                                .tit_img {
                                    width: 32rpx;
                                    height: 32rpx;
                                    margin: 0rpx 10rpx 3rpx 0rpx;
                                    vertical-align: bottom;
                                }
                            }

                            .light {
                                margin-left: 10rpx;
                                display: inline-block;
                                border: 2rpx solid #89ccff;
                                border-radius: 6rpx;
                                font-size: 24rpx;
                                font-weight: 400;
                                text-align: left;
                                color: #0091ff;
                                padding: 0rpx 5rpx;
                            }

                            .info {
                                color: #666666;

                                text {
                                    color: #cccccc;
                                    margin: 0rpx 10rpx;
                                }
                            }

                            .infoTips {
                                width: 158rpx;
                                height: 32rpx;
                                background: #fff0e6;
                                border-radius: 16rpx;
                                font-size: 22rpx;
                                font-weight: 400;
                                color: #fa6400;
                                text-align: center;
                                margin-top: 10rpx;

                            }
                        }

                        .contElevar_Right {
                            flex: 0 0 180rpx;
                            display: flex;
                            justify-content: flex-end;

                            .middle_R {

                                display: flex;
                                margin-top: 20rpx;
                            }

                            .nameContent {
                                display: flex;
                                flex: 1;
                                flex-wrap: wrap;
                                justify-content: flex-end;

                            }

                            .nameArea {
                                display: flex;
                                align-items: center;
                            }
                        }

                    }

                    .actElevar {
                        background-color: #f8f8f8;
                        border: 4rpx solid;
                        border-left-color: #0091ff;
                        border-top-color: transparent;
                        border-bottom-color: transparent;
                        border-right-color: transparent;
                    }
                }
            }

            .question-label {
                color: #999999;
                font-size: 24rpx;
                margin-right: 12rpx;
            }

            .question-count {
                color: #333;
                font-size: 24rpx;
            }

            .question-tag {
                font-size: 24rpx;
                padding: 0 8rpx;
                border-radius: 4rpx;
                color: #E02020;
                border: 2rpx solid #E02020;
            }
        }

        .content_R {
            overflow-y: auto;
            flex: 1;

            .R_text {
                padding: 40rpx 40rpx 0 20rpx;

                .lines {
                    margin-top: 30rpx;
                    border-bottom: 2rpx solid #eeeeee;
                }

                text:nth-child(1) {
                    display: block;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333333;
                }

                text:nth-child(2) {
                    display: block;
                    border: 2rpx solid #0091ff;
                    border-radius: 8rpx;
                    font-size: 24rpx;
                    color: #0091ff;
                    padding: 5rpx;
                    margin-top: 6rpx;
                    width: 112rpx;
                    text-align: center;
                }
            }
        }
    }

    .empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 100rpx;
        width: 710rpx;
        height: calc(100% - 400rpx);

        .circle {
            width: 112rpx;
            height: 112rpx;
            border-radius: 50%;
        }

        image {
            width: 112rpx;
            height: 112rpx;
        }

        .title {
            font-size: 28rpx;
            color: #666;
            font-weight: 400;
            margin-top: 10rpx;
        }

        .tips {
            font-size: 24rpx;
            color: #999;
        }
    }

}

.memberName {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    font-size: 20rpx;
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    background-color: #0091ff;
    color: #fff;
    margin-right: 12rpx;

    .people {
        width: 54rpx;
        position: absolute;
        left: 0;
        top: 40rpx;
        background: #faf1d9;
        border: 0.5px solid #d5c498;
        border-radius: 4rpx;
        box-sizing: border-box;
        font-size: 16rpx;
        text-align: center;
        color: #8d6800;
    }
}

@keyframes scaleFrames {
    from {
        transform: translateY(110%);
    }

    to {
        transform: translateY(0);
    }
}

@keyframes fadeInOut {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

.calendarEdit {
    background-color: #fff;
    height: 678rpx;
    border-radius: 8rpx 8rpx 0rpx 0rpx;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    animation: scaleFrames 0.3s ease;

    .edit_bor {
        width: 100%;
        padding: 20rpx 0;

        .down-btn {
            width: 64rpx;
            height: 10rpx;
            background: #d8d8d8;
            border-radius: 6rpx;
            margin: 0 auto;
        }
    }

    .edit_content {
        width: 680rpx;
        margin: 0 auto;

        .executive_tit {
            margin-bottom: 20rpx;
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
        }

        .executive {
            display: flex;
            flex-direction: column;
            margin-bottom: 20rpx;
            padding-bottom: 20rpx;

            .executive_gr {
                margin-bottom: 20rpx;
            }

            .executive_user {
                display: flex;
                margin-bottom: 10rpx;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid #eee;
                padding: 20rpx 0;

                .signStatus {
                    color: #FA6400;
                    text-align: center;
                    background-color: #ffefe3;
                    font-size: 24rpx;
                    font-weight: 400;
                    margin: 0 10rpx;
                    padding: 0 10rpx;
                }
            }

            .last {
                border: none;
            }
        }
    }
}
</style>
